﻿using AutoFixture;
using AutoFixture.Kernel;
using DataInit.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace DataInit.DataContexts.SpecimenBuilders
{
    public class StringPropertyTruncateSpecimenBuilder<TEntity> : ISpecimenBuilder
    {
        private readonly PropertyInfo _prop;
        private readonly PTDBContext DBContext;
        private static IEnumerable<LoginOperator> operatorEntities;

        public StringPropertyTruncateSpecimenBuilder(Expression<Func<TEntity, Guid>> getter, PTDBContext DBContext)
        {
            _prop = (PropertyInfo)((MemberExpression)getter.Body).Member;
            this.DBContext = DBContext;
        }

        public object Create(object request, ISpecimenContext context)
        {
            var pi = request as PropertyInfo;

            return pi != null && AreEquivalent(pi, _prop)
                ? GetRadomOperatorId()
                : (object)new NoSpecimen();
        }

        private bool AreEquivalent(PropertyInfo a, PropertyInfo b)
        {
            return a.DeclaringType == b.DeclaringType
                   && a.Name == b.Name;
        }

        Guid GetRadomOperatorId()
        {
            if (operatorEntities == null)
            {

                operatorEntities = DBContext.LoginOperatorEntity.AsQueryable().ToList();
            }
            Random rand = new Random();

            int value = rand.Next(0, operatorEntities.Count());
            var entity = operatorEntities.ElementAt(value);
            return entity != null ? entity.OperatorId : Guid.Empty;



        }
    }
}